package org.water.garden.activity.chat;

import java.util.Date;

import org.water.garden.R;
import org.water.garden.core.Intents;
import org.water.garden.view.MessageListAdapter;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.provider.Im;
import android.provider.Im.Contacts;
import android.provider.Im.MessageType;
import android.provider.Im.Messages;
import android.provider.Im.Provider;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author sshwsfc@gmail.com
 * 
 * Main Chat window show message for this account and contact.
 */
public class ChatWindow extends Activity implements OnClickListener {

	private static final String LOG_TAG = "ChatWindow";

	EditText mUsernameField;
	ImageButton mSendButton;
	ImageView mContactIcon;
	ImageView mStatusIcon;
	TextView mChatTo;
	TextView mChatEmail;
	EditText mMsg;
	Cursor mCursor;
	ListView mListMessages;
	Integer contactId;
	String providerName;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.chat_window);

		mSendButton = (ImageButton) findViewById(R.id.chat_msg_send_button);
		mSendButton.setOnClickListener(this);
		mSendButton.setEnabled(false);
		
		String chatId = getIntent().getData().getLastPathSegment();

		mCursor = Contacts.query(getContentResolver(), new String[] { 
			Contacts._ID, Contacts.NICKNAME, Contacts.USERNAME, Contacts.PROVIDER,
			Contacts.ACCOUNT, Im.Presence.PRESENCE_STATUS, Im.Presence.PRESENCE_CUSTOM_STATUS }, 
			"chats._id = " + chatId, null);

		if (mCursor.first()) {
			Cursor pcursor = getContentResolver().query(Provider.CONTENT_URI, new String[] { Provider.NAME }, "_id=?",
					new String[] { Integer.toString(mCursor.getInt(3)) }, null);

			if (pcursor.first()) {
				providerName = pcursor.getString(0);
			}
			pcursor.close();

			mContactIcon = (ImageView) findViewById(R.id.contact_icon);
			mContactIcon.setImageResource(android.R.drawable.contact_pager);

			mStatusIcon = (ImageView) findViewById(R.id.contact_status);
			
			int mode = mCursor.getInt(mCursor.getColumnIndex(Im.Presence.PRESENCE_STATUS));
			if(mode == Im.Presence.AVAILABLE){
				mStatusIcon.setImageResource(R.drawable.msn_online);
			}else if(mode == Im.Presence.OFFLINE){
				mStatusIcon.setImageResource(R.drawable.msn_offline);
			}else {
				mStatusIcon.setImageResource(R.drawable.msn_busy);
			}

			mChatTo = (TextView) findViewById(R.id.msn_account_label);
			mChatTo.setText(mCursor.getString(1));

			mChatEmail = (TextView) findViewById(R.id.msn_account_email);
			mChatEmail.setText(mCursor.getString(2));

			mMsg = (EditText) findViewById(R.id.msn_msg_label);
			mMsg.setOnKeyListener(keyListenter);
			
			mListMessages = (ListView) findViewById(R.id.listMessages);

			StringBuilder sb = new StringBuilder();
			sb.append(Messages.ACCOUNT).append("=? AND ");
			sb.append(Messages.CONTACT).append("=?");

			Cursor cursor = managedQuery(Im.Messages.CONTENT_URI, new String[] { 
					Messages._ID, Messages.BODY, Messages.DATE, Messages.TYPE, Messages.SHOW_TIME_STAMP
					}, sb.toString(),
					new String[] { Integer.toString(mCursor.getInt(4)), mCursor.getString(2) }, null);

			ListAdapter adapter = new MessageListAdapter(ChatWindow.this, cursor);
			adapter.registerDataSetObserver(observer);
			
			mListMessages.setAdapter(adapter);
			mSendButton.setEnabled(true);
		} else {
			Toast.makeText(this, "Cann't find contact with url : " + getIntent().getData(), 300).show();
		}
	}

	private OnKeyListener keyListenter = new OnKeyListener(){

		public boolean onKey(View view, int code, KeyEvent keyEvent){
			if(code == KeyEvent.KEYCODE_DPAD_CENTER){
				ChatWindow.this.onClick(view);
			}
			return true;
		}
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		if(null != mListMessages){
			//mListMessages.scrollTo(0, mListMessages.getHeight());
		}
	}

	private DataSetObserver observer = new DataSetObserver() {
	
		@Override
		public void onInvalidated() {
		}
	
		@Override
		public void onChanged() {
			if(null != mListMessages){
				//mListMessages.scrollTo(1, 1);
			}
		}
	
	};
	
	public void onClick(View view) {
		if(mMsg.getText().toString() !=null && !mMsg.getText().toString().equals("")){
			Intent intent = new Intent(Intents.SEND_MESSAGE);
			if (providerName != null) {
				intent.addCategory(Intents.CATEGORY_PROVIDER_PREFIX + providerName);
			}
			ContentValues cvs = new ContentValues();
			
			cvs.put(Messages.ACCOUNT, mCursor.getInt(4));
			cvs.put(Messages.PROVIDER, mCursor.getInt(3));
			cvs.put(Messages.CONTACT, mCursor.getString(2));
			cvs.put(Messages.BODY, mMsg.getText().toString());
			cvs.put(Messages.TYPE, MessageType.OUTGOING);
			cvs.put(Messages.DATE, (new Date()).getTime());
			
			intent.putExtra(Messages.CONTENT_ITEM_TYPE, cvs);
			
			startActivity(intent);
		}else{
			Toast.makeText(this, "Cann't send blank message.", 300).show();
		}

		mMsg.setText("");
		mMsg.requestFocus();
	}

}
